#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <signal.h>
#include <pthread.h>

int quitflag;
sigset_t mask;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;

void* thr_fn(void* arg) {
	int err, signo;
	for ( ; ; ) {
		err = sigwait(&mask, &signo);
		if (err != 0) {
			printf("sigwait error\n");
			return NULL;
		}

		switch (signo) {
		case SIGINT:
			printf("interrupt\n");
			break;
		case SIGQUIT:
			pthread_mutex_lock(&lock);
			quitflag = 1;
			pthread_mutex_unlock(&lock);
			pthread_cond_signal(&wait);
			return NULL;
		default:
			printf("other signal\n");
			break;
		}
	}
}

int main() {
	int err;
	sigset_t oldmask;
	pthread_t tid;

	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	sigaddset(&mask, SIGQUIT);

	if ((err=pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
		printf("block error\n");
		return -1;
	}

	err = pthread_create(&tid, NULL, thr_fn, NULL);
	pthread_mutex_lock(&lock);
	while (quitflag == 0)
		pthread_cond_wait(&wait, &lock);
	pthread_mutex_unlock(&lock);

	quitflag = 0;
	sigprocmask(SIG_SETMASK, &oldmask, NULL);

	return 0;
}